<template>
  <el-form :model="form" ref="ruleFormRef" :rules="rules" status-icon :label-position="labelPosition" label-width="120px"
    :inline="true" class="demo-form-inline">
    <el-form-item label="会议名称" prop="name">
      <el-input maxlength="50" v-model="form.name" :disabled="1" />
    </el-form-item>

    <el-form-item label="会议时间" prop="mettingTime">
      <el-date-picker v-model="form.mettingTime" format="YYYY-MM-DD" type="date" placeholder="选择日期" clearable
        @change="handleChangeDate" :disabled="1"/>
    </el-form-item>

    <el-form-item label="会议类别" prop="className">
      <SelectOption :selectValue="form.className" :options="data.gjhMeetingType" @change-value="changeValue" :disabled="1">
      </SelectOption>
    </el-form-item>

    <el-form-item label="参与形式" prop="joinMethod">
      <SelectOption :selectValue="form.joinMethod" :options="data.gjhShapeSelect" @change-value="changeValue1" :disabled="1">
      </SelectOption>
    </el-form-item>

    <el-form-item label="所属单位" prop="unitName">
      <!-- <SelectOption :selectValue="form.unitName" :options="data.orgAllList" @change-value="changeValue2"> </SelectOption> -->

      <popup-tree-input :data="orgAllList" :props="data.popupTreeProps" :prop="deptForm.parentName == null
          ? $t('message.org.top_menu')
          : form.unitName
        " :node-key="'' + deptForm.parentId" :current-change-handle="changeValue2" :disabled="1" />

    </el-form-item>

    <el-form-item label="联系人" prop="contractUser">
      <!-- <SelectOption :selectValue="form.contractUser" :options="data.userAllList" @change-value="changeValue3">
      </SelectOption> -->
      <user-list-modal
        v-model="form.contractUser"
        @update:modelValue="changeValue3"
        :default-users="[]"
        :multiple="false"
        :devType="'platform'" :disabled="1"
      />
    </el-form-item>

    <el-form-item label="联系方式" prop="contractMethod">
      <el-input maxlength="20" v-model="form.contractMethod" :disabled="1" />
    </el-form-item>

    <el-form-item label="报告题目" prop="reportTitle">
      <el-input maxlength="100" v-model="form.reportTitle" :disabled="1" />
    </el-form-item>

    <el-form-item style="width: 100%" label="参会人员" prop="joinPersons">
      <div class="selectLabel">
        <el-tag v-for="tag in callPerson" :key="tag.id" class="mx-1" closable  :disabled="1">
<!--        <el-tag v-for="tag in callPerson" :key="tag.id" class="mx-1" closable @close="handleClosePerson(tag)">-->
          {{ tag.username }}
        </el-tag>
      </div>
<!--      <span class="addLabel" @click="addPersonBox">选择人员</span>-->
    </el-form-item>

    <el-form-item label="备注" class="labelHeight" style="width: 100%">
      <el-input v-model="form.remark" :autosize="{ minRows: 2 }" maxlength="200" type="textarea" placeholder="请输入"  :disabled="1"/>
    </el-form-item>
  </el-form>

  <el-dialog v-model="data.addPerson" append-to-body width="60%" top="10vh" :show-close="false"
    :close-on-click-modal="false">
    <template #title>
      <el-tabs v-model="data.activeName" class="demo-tabs">
        <el-tab-pane label="员工列表" name="first">
          <div>
            <el-row>
              <el-col :span="24" align="right">
                <el-input v-model="data.params.name" placeholder="姓名" style="width: 150px; margin-right: 15px" />
                <SelectOption :options="data.orgAllList" style="width: 200px;margin-right: 15px;" :placeholder="'归属单位'"
                  @change-value="changeValueUnit">
                </SelectOption>
                <el-button class="ordinary" @click="search()">搜索</el-button>
                <Table :tableArr="data.userList" :pagination="data.page" :columns="data.columns" :operate="true"
                  @delectTable="delectIds" @selectItem="selectItemFn" :total="data.page.total">
                </Table>
              </el-col>
            </el-row>

          </div>
        </el-tab-pane>
      </el-tabs>
    </template>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closePersonbox">关闭</el-button>
        <el-button type="primary" @click="save()">选择</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts">
import UserListModal from '@/views/project/components/UserListModal/index.vue'
import { getUserList } from '@/views/science/api/common'
import PopupTreeInput from '@/views/science/components/PopupTreeInput/index.vue'
import SelectOption from '@/views/science/components/selectOption/index.vue'
import Table from '@/views/science/components/table/table.vue'
import { computed, reactive, ref, watch } from 'vue'
import { useStore } from 'vuex'
import tableData from './tableHeader.json'

export default {
  components: {
    SelectOption,UserListModal,
    Table,PopupTreeInput
  },
  emits: {
    valueFlag: null,
  },
  props:{
    orgAllList: {
      type: Array,
      required: true,
    },
  },
  setup(props, { emit }) {

    const deptForm = {
            parentId: 0,
            parentName: '',
        }
    const store = useStore()
    const labelPosition = ref('right')

    const data = reactive({
      popupTreeProps: {
                label: 'name',
                children: 'children',
            },
      activeName: ref('first'),
      addPerson: false,
      columns: tableData.userList,
      page: { page: 1, limit: 10, total: 0 },
      params: {
        current: 1,
        size: 10,
        name: "",
        unitOrg: ""
      },
      ids: '',
      userList: [],

      innerValue: '',
      outsideValue: '',

      orgAllList: computed(() => store.state.technologyStrength.orgAllList),
      gjhMeetingType: computed(() => store.state.technologyStrength.gjhMeetingType),
      gjhShapeSelect: computed(() => store.state.technologyStrength.gjhShapeSelect),
      userAllList: computed(() => store.state.technologyStrength.userAllList),
    })

    const form = reactive(store.state.technologyStrength.meetingInfo)
    watch(form, (newValue, oldValue) => {
      store.commit('technologyStrength/getmeetingInfo', { ...form })
    });
    //分页获取人员列表
    const getUseList = async () => {
      const res = await getUserList(data.params)
      data.userList = res.data.data.records
      data.page.total = res.data.data.total
    }

    const changeValueUnit = (item) => {
      data.params.unitOrg = item.id
    }

    const changeValue = (item) => {
      form.className = item.itemText
      form.classId = item.itemValue
    }
    const changeValue1 = (item) => {
      form.joinMethod = item.itemText
      form.joinMethodId = item.itemValue
    }
    const changeValue2 = (item) => {
      form.unitName = item.name
      form.unitId = item.id
    }
    const changeValue3 = (item) => {
      form.contractUser = item.cname
      form.contractUserId = item.userId
      form.contractMethod = item.phone
    }

    const delectIds = (ids) => {
      data.ids = ids
    }

    const arr0 = ref(form.joinPersons ? form.joinPersons.split(',') : [])
    const arr1 = ref(form.joinPersonIds ? form.joinPersonIds.split(',') : [])
    let arr2: any = []
    arr0.value.map((item, index) => {
      const obj = {
        username: item,
        userId: arr1.value[index]
      }
      arr2.push(obj)
    })

    const callPerson: any = ref([...arr2])
    const person: any = ref([])

    const selectItemFn = (item) => {
      item.filter(
        (item, index) => {
          const obj = {
            username: item.cname,
            userId: item.userId
          }
          if (JSON.stringify(person.value).indexOf(JSON.stringify(obj)) == -1) person.value.push(obj);
        }
      )
    }


    const addPersonBox = () => {
      data.userList = []
      getUseList()
      data.addPerson = true
    }

    const handleClosePerson = (tag) => {
      callPerson.value.splice(callPerson.value.indexOf(tag), 1)
      handleSelectPerson(callPerson)
    }

    const closePersonbox = () => {
      data.addPerson = false
      person.value = []
    }

    const save = () => {
      data.addPerson = false
      person.value.filter(
        (item, index) => {
          if (JSON.stringify(callPerson.value).indexOf(JSON.stringify(item)) == -1) callPerson.value.push(item);
        }
      )
      person.value = []
      handleSelectPerson(callPerson)
    }

    const arrname: any = reactive([])
    const arrid: any = reactive([])
    const handleSelectPerson = (val) => {
      val.value.map((item) => {
        if (arrname.indexOf(item.username) == -1) arrname.push(item.username)
        if (arrid.indexOf(item.userId) == -1) arrid.push(item.userId)
      })
      form.joinPersons = arrname.join(',')
      form.joinPersonIds = arrid.join(',')
    }


    const rules = reactive({
      name: [
        { required: true, message: '请输入会议名称', trigger: 'blur' },
      ],
      mettingTime: [
        { required: true, message: '请选择会议时间', trigger: 'change', },
      ],
      className: [
        { required: true, message: '请选择会议类别', trigger: 'change', },
      ],
      joinMethod: [
        { required: true, message: '请选择参与形式', trigger: 'change', },
      ],
      unitName: [
        { required: true, message: '请选择所属单位', trigger: 'change', },
      ],
      contractUser: [
        { required: true, message: '请选择联系人', trigger: 'change', },
      ],
      contractMethod: [
        { required: false, message: '请输入电话号码', trigger: 'change', },
        { pattern: /^1[3456789]\d{9}$/, message: '电话号码格式不正确', trigger: 'blur' },
      ],
      reportTitle: [
        { required: true, message: '请输入报告题目', trigger: 'blur', },
      ],
      joinPersons: [
        { required: true, message: '请选择参会人员', trigger: 'change', },
      ],
    })

    const ruleFormRef = ref()
    const submitForm = async () => {
      await ruleFormRef.value.validate((valid, fields) => {
        if (valid) {
          emit('valueFlag', true)
          console.log('submit!')
        } else {
          emit('valueFlag', false)
        }
      })
    }

    const handleChangeDate = (val) => {
      const year = val.getFullYear(); // 获取年份
      const month = (val.getMonth() + 1) < 10 ? '0' + (val.getMonth() + 1) : (val.getMonth() + 1); // 获取月份，需要加1
      const day = val.getDate() < 10 ? '0' + val.getDate() : val.getDate(); // 获取日期
      const formattedDate = `${year}-${month}-${day}`;
      form.mettingTime = formattedDate
      store.commit('technologyStrength/getmeetingInfo', { ...form })
    }

    const search = () => {
      data.page.page = 1
      getUseList()
    }

    return {
      labelPosition,
      data,
      form,
      rules,
      ruleFormRef,
      submitForm,
      handleChangeDate,
      delectIds,
      search,
      changeValueUnit,
      selectItemFn,
      closePersonbox,
      callPerson,
      deptForm,

      changeValue,
      changeValue1,
      changeValue2,
      changeValue3,

      addPersonBox,
      handleClosePerson,
      save,
    }
  },
}
</script>
<style lang="scss" scoped>
.demo-form-inline .el-form-item {
  width: 48%;
}

:global(.el-dialog__body) {
  padding: 0;
}

:deep(.labelHeight .el-form-item__label) {
  line-height: 20px;
}

:deep(.el-date-editor.el-input) {
  width: 100%;
}

:deep(.el-date-editor.el-input__inner) {
  width: 100%;
}

:deep(.demo-form-inline .el-select) {
  width: 100%;
  margin: 0;
}

.el-select {
  width: 100%;
  margin: 0;
}

.selectLabel {
  width: 70%;
  min-height: 40px;
  height: 100%;
  // line-height: 40px;
  padding: 0 15px;
  border: 1px solid #ccc;
  border-radius: 6px;
  display: inline-block;
  vertical-align: middle;
}

.addLabel {
  display: inline-block;
  width: 120px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  background-color: #169bd5;
  border-radius: 6px;
  color: #fff;
  margin-left: 15px;
}

.unitBox {
  width: 100%;
  margin: 30px 0;

  .title {
    padding: 15px 0;
    border-bottom: 1px solid #ccc;
  }

  .tagBox {
    line-height: 40px;
    margin-top: 15px;
    border: 1px solid #ccc;
    border-radius: 8px;
    padding: 10px 15px;
  }
}

.el-tag {
  margin-right: 10px;
}
</style>
